package com.example.photo_sharing.page.userInfo;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.os.NetworkOnMainThreadException;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.example.photo_sharing.MainActivity;
import com.example.photo_sharing.R;
import com.example.photo_sharing.global.App;
import com.example.photo_sharing.tool.Impl.UserInfoSPImpl;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Login extends AppCompatActivity{

    private App app;
    private EditText acc;
    private EditText pwd;

    private SharedPreferences sharedPreferences;
    private UserInfoSPImpl usp ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        app = (App)getApplication();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        sharedPreferences = getSharedPreferences("userInfo",MODE_PRIVATE);
        usp = new UserInfoSPImpl(sharedPreferences);

        //隐藏标题栏
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide(); //隐藏标题栏
        }

        //跳转到注册的事件
        Button btn = (Button)findViewById(R.id.go_to_register);
        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Intent i = new Intent(Login.this , Register.class);
                startActivity(i);
            }
        });

        //添加登录按钮的事件
        Button btn2 = (Button)findViewById(R.id.bt_login);
        btn2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                acc = findViewById(R.id.et_account);
                pwd = findViewById(R.id.et_pwd);

                System.out.println("123");
                post();




            }
        });
    }

    private void post(){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/photo/user/login?"
                    + "password=" + pwd.getText().toString()
                    + "&username=" + acc.getText().toString();

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json, text/plain, */*")
                    .add("appId", app.getAppId())
                    .add("appSecret", app.getAppSecret())
                    .add("Content-Type", "application/json")
                    .build();

            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, ""))
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            e.printStackTrace();
            System.out.println("失败");
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            String responseData = response.body().string();
            JSONObject jsonObject  = JSONObject.parseObject(responseData).getObject("data", JSONObject.class);
            int code = JSONObject.parseObject(responseData).getInteger("code");
            String msg = JSONObject.parseObject(responseData).getString("msg");

            System.out.println(responseData);
            System.out.println(jsonObject);
            System.out.println(code);

            if(code == 200){
                String userId = jsonObject.getString("id");
                String username = jsonObject.getString("username");
                String avatar = jsonObject.getString("avatar");
                String introduce = jsonObject.getString("introduce");
                int sex = jsonObject.getIntValue("sex");

                usp.saveInfo(introduce,sex,userId,avatar,username);
                usp.Login_in();
            }

            Intent i = new Intent(Login.this , MainActivity.class);
            startActivity(i);

            Looper.prepare();
            Toast.makeText(Login.this,msg,Toast.LENGTH_LONG).show();//创建toast类，并定义显示内容
            Looper.loop();
        }
    };
}
